package com.cn.ZhiKeDianShang.ui.fragment;

import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;

import androidx.annotation.Nullable;

import android.os.Handler;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.TextView;

import com.baidu.location.BDAbstractLocationListener;
import com.baidu.location.BDLocation;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.MapStatus;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.MyLocationData;
import com.baidu.mapapi.model.LatLng;
import com.cn.ZhiKeDianShang.AppConfig;
import com.cn.ZhiKeDianShang.Oss.OssService;
import com.cn.ZhiKeDianShang.R;
import com.cn.ZhiKeDianShang.base.BaseFragment;
import com.cn.ZhiKeDianShang.model.TaskInfoBean;
import com.cn.ZhiKeDianShang.model.event.refushBean;
import com.cn.ZhiKeDianShang.model.event.sendImageBean;
import com.cn.ZhiKeDianShang.model.request.SumitTaskJson;
import com.cn.ZhiKeDianShang.model.response.ImageBean;
import com.cn.ZhiKeDianShang.presenter.MineFragmentPresenter;
import com.cn.ZhiKeDianShang.presenter.view.MineFragmentView;
import com.cn.ZhiKeDianShang.ui.activity.OrderDetailActivity;
import com.cn.ZhiKeDianShang.ui.adapter.GridViewAdapter;
import com.cn.ZhiKeDianShang.util.JsonUitl;
import com.cn.ZhiKeDianShang.util.MultiImagePreview.AppConstant;
import com.cn.ZhiKeDianShang.util.MultiImagePreview.MultiImagePreviewActivity;
import com.cn.ZhiKeDianShang.util.Netdialog.StyledDialog;
import com.cn.ZhiKeDianShang.util.PrefShare;
import com.cn.ZhiKeDianShang.util.ProgressDialogFragment;
import com.cn.ZhiKeDianShang.util.ToastUtil;
import com.cn.ZhiKeDianShang.util.view.MyGridView;
import com.cn.ZhiKeDianShang.xuanhttplibrary.okhttp.HttpUtils;
import com.cn.ZhiKeDianShang.xuanhttplibrary.okhttp.callback.BaseCallback;
import com.cn.ZhiKeDianShang.xuanhttplibrary.okhttp.result.ObjectResult;
import com.cn.ZhiKeDianShang.xuanhttplibrary.okhttp.result.Result;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import okhttp3.Call;

/**
 * 我的
 * Created by chengaofu on 2017/6/21.
 */

public class SubmitFreagment extends BaseFragment<MineFragmentView, MineFragmentPresenter> implements MineFragmentView {


    @BindView(R.id.et_taobao_number)
    EditText etTaobaoNumber;
    @BindView(R.id.grid_photo)
    MyGridView gridPhoto;
    @BindView(R.id.grid_other)
    MyGridView gridOther;
    @BindView(R.id.et_remark)
    EditText etRemark;
    @BindView(R.id.bmapView)
    MapView bmapView;
    @BindView(R.id.tv_commit)
    TextView tv_commit;


    TaskInfoBean.TaskinfoBean mTaskinfoBean;
    String taskId;

    //图片本地地址集合
    private ArrayList<ImageBean> photoPictureList;
    private GridViewAdapter mPictureAdapter;

    private ArrayList<ImageBean> otherPictureList;
    private GridViewAdapter mOtherAdapter;
    int sumNumber = 6;
    //是不是照片拍摄    true为照片拍摄   false为 其他照片
    boolean IsGridPhoto;
    double latitude;
    double longitude;

    private BaiduMap mBaiduMap;

    Unbinder unbinder;
    private ProgressDialogFragment mProgressDialog;
    static OrderDetailActivity.showPhotoPop mShowPhotoPop;


    public static SubmitFreagment getInstance(String taskId, TaskInfoBean.TaskinfoBean bean, OrderDetailActivity.showPhotoPop showPhotoPop) {
        mShowPhotoPop = showPhotoPop;
        SubmitFreagment fragment = new SubmitFreagment();
        Bundle bundle = new Bundle();
        bundle.putString("taskId", taskId);
        bundle.putSerializable("bean", bean);
        fragment.setArguments(bundle);
        return fragment;
    }


    public class MyLocationListener extends BDAbstractLocationListener {
        @Override
        public void onReceiveLocation(BDLocation location) {
            //mapView 销毁后不在处理新接收的位置
            if (location == null || bmapView == null) {
                return;
            }
            int errorCode = location.getLocType();
            Log.d("Debug", "到达地址回调这里" + location.getProvince() + errorCode);
//            ToastUtil.showShort("定位返回code--" + errorCode);
            latitude = location.getLatitude();    //获取纬度信息
            longitude = location.getLongitude();    //获取经度信息
            Log.d("Debug", "获取的经纬度为" + latitude + "---------" + longitude);
//            MyLocationData locData = new MyLocationData.Builder()
//                    .accuracy(location.getRadius())
//                    // 此处设置开发者获取到的方向信息，顺时针0-360
//                    .direction(location.getDirection()).latitude(location.getLatitude())
//                    .longitude(location.getLongitude()).build();
//

            /*获取当前位置 并显示到地图上*/
            MyLocationData.Builder locationBuilder = new MyLocationData.Builder();
            locationBuilder.latitude(location.getLatitude());
            locationBuilder.longitude(location.getLongitude());
            MyLocationData locationData = locationBuilder.build();
            mBaiduMap.setMyLocationData(locationData);

            LatLng ll = new LatLng(location.getLatitude(), location.getLongitude());
            MapStatus.Builder builder = new MapStatus.Builder();
            builder.target(ll).zoom(18.0f);
            mBaiduMap.animateMapStatus(MapStatusUpdateFactory.newMapStatus(builder.build()));

//            mBaiduMap.setMyLocationData(locData);
        }
    }

    LocationClient locationClient;

    /**
     * 初始化定位参数配置
     */

    private void initLocationOption() {
        mBaiduMap = bmapView.getMap();
        // 开启定位图层
        mBaiduMap.setMyLocationEnabled(true);
        mBaiduMap.setMapType(BaiduMap.MAP_TYPE_NORMAL);
        // 开启室内图
//        mBaiduMap.setIndoorEnable(true);
//定位服务的客户端。宿主程序在客户端声明此类，并调用，目前只支持在主线程中启动
        locationClient = new LocationClient(getActivity());
//声明LocationClient类实例并配置定位参数
        LocationClientOption locationOption = new LocationClientOption();
        MyLocationListener myLocationListener = new MyLocationListener();
//注册监听函数
        locationClient.registerLocationListener(myLocationListener);
//可选，默认高精度，设置定位模式，高精度，低功耗，仅设备
        locationOption.setLocationMode(LocationClientOption.LocationMode.Hight_Accuracy);
//可选，默认gcj02，设置返回的定位结果坐标系，如果配合百度地图使用，建议设置为bd09ll;
        locationOption.setCoorType("bd09ll");
//可选，默认0，即仅定位一次，设置发起连续定位请求的间隔需要大于等于1000ms才是有效的
        locationOption.setScanSpan(0);
//可选，设置是否需要地址信息，默认不需要
        locationOption.setIsNeedAddress(true);

//可选，默认false，设置是否开启Gps定位
        locationOption.setOpenGps(false);
//设置打开自动回调位置模式，该开关打开后，期间只要定位SDK检测到位置变化就会主动回调给开发者，该模式下开发者无需再关心定位间隔是多少，定位SDK本身发现位置变化就会及时回调给开发者
        locationOption.setOpenAutoNotifyMode();
//设置打开自动回调位置模式，该开关打开后，期间只要定位SDK检测到位置变化就会主动回调给开发者
        locationOption.setOpenAutoNotifyMode(10000, 1, LocationClientOption.LOC_SENSITIVITY_HIGHT);
//需将配置好的LocationClientOption对象，通过setLocOption方法传递给LocationClient对象使用
        locationClient.setLocOption(locationOption);
//开始定位
        locationClient.start();
    }


    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Log.d("Debug", "到达onCreate方法中----------------------");
        Bundle arguments = getArguments();
        taskId = arguments.getString("taskId");
        mTaskinfoBean = (TaskInfoBean.TaskinfoBean) arguments.getSerializable("bean");
    }


    @Override
    protected void initViewsAndEvents() {
        mBaiduMap = bmapView.getMap();
        // 开启定位图层
        mBaiduMap.setMyLocationEnabled(true);
        mBaiduMap.setMapType(BaiduMap.MAP_TYPE_NORMAL);
        initLocationOption();
        //初始化OssService类，参数分别是Content，accessKeyId，accessKeySecret，endpoint，bucketName（后4个参数是您自己阿里云Oss中参数）
        ossService = new OssService(getActivity(), accessKeyId, accessKeySecret, endpoint, bucketName);
        //初始化OSSClient
        ossService.initOSSClient();
        photoPictureList = new ArrayList<>();
        mPictureAdapter = new GridViewAdapter(getActivity(), photoPictureList, sumNumber, mTaskinfoBean.getStatus() + "", new GridViewAdapter.onGridViewAdapterClick() {
            @Override
            public void onItemClick(int position) {
                int viewType = mPictureAdapter.getItemViewType(position);
                if (viewType == 1) {
                    if (!(mTaskinfoBean.getStatus() == 4)) {
                        IsGridPhoto = true;
                        //弹起选择 相机还是相册
                        mShowPhotoPop.showPhotoPop(taskId, sumNumber - photoPictureList.size());
                    }
                } else {
                    //查看图片
                    ArrayList<String> imageList = new ArrayList<>();
                    for (int i = 0; i < photoPictureList.size(); i++) {
                        imageList.add(photoPictureList.get(i).getOssUrl());
                    }
                    Intent intent = new Intent(getActivity(), MultiImagePreviewActivity.class);
                    intent.putExtra(AppConstant.EXTRA_IMAGES, imageList);
                    intent.putExtra(AppConstant.EXTRA_POSITION, position);
                    intent.putExtra(AppConstant.EXTRA_CHANGE_SELECTED, false);
                    startActivity(intent);
                }
            }

            @Override
            public void delete(int position) {
                IsGridPhoto = true;
                //上传到cos地址拼接
                StringBuilder deletest = new StringBuilder();
                for (int i = 0; i < photoPictureList.size(); i++) {
                    ImageBean imageBean = photoPictureList.get(i);
                    if (i != position) {
                        if (i < photoPictureList.size() - 1) {
                            deletest.append(imageBean.getOssUrl() + ",");
                        } else {
                            deletest.append(imageBean.getOssUrl());
                        }
                    }

                }
                Log.d("Debug", "删除之后上传的地址" + deletest.toString());
                updateTaskinfo(deletest.toString() + "", 1, position);
            }
        });
        gridPhoto.setAdapter(mPictureAdapter);


        otherPictureList = new ArrayList<>();
        mOtherAdapter = new GridViewAdapter(getActivity(), otherPictureList, sumNumber, mTaskinfoBean.getStatus() + "", new GridViewAdapter.onGridViewAdapterClick() {
            @Override
            public void onItemClick(int position) {
                int viewType = mOtherAdapter.getItemViewType(position);

                if (viewType == 1) {
                    if (!(mTaskinfoBean.getStatus() == 4)) {
                        //弹起选择 相机还是相册
                        IsGridPhoto = false;
                        mShowPhotoPop.showPhotoPop(taskId, sumNumber - otherPictureList.size());
                    }

                } else {
                    //查看图片
                    ArrayList<String> imageList = new ArrayList<>();
                    for (int i = 0; i < otherPictureList.size(); i++) {
                        imageList.add(otherPictureList.get(i).getOssUrl());
                    }
                    Intent intent = new Intent(getActivity(), MultiImagePreviewActivity.class);
                    intent.putExtra(AppConstant.EXTRA_IMAGES, imageList);
                    intent.putExtra(AppConstant.EXTRA_POSITION, position);
                    intent.putExtra(AppConstant.EXTRA_CHANGE_SELECTED, false);
                    startActivity(intent);
                }
            }

            @Override
            public void delete(int position) {
                IsGridPhoto = false;
                //上传到cos地址拼接
                StringBuilder deletest = new StringBuilder();
                for (int i = 0; i < otherPictureList.size(); i++) {
                    ImageBean imageBean = otherPictureList.get(i);
                    if (i != position) {
                        if (i < otherPictureList.size() - 1) {
                            deletest.append(imageBean.getOssUrl() + ",");
                        } else {
                            deletest.append(imageBean.getOssUrl());
                        }
                    }

                }
                Log.d("Debug", "删除之后上传的地址" + deletest.toString());
                updateTaskinfo(deletest.toString() + "", 1, position);
            }
        });
        gridOther.setAdapter(mOtherAdapter);


        if (mTaskinfoBean != null) {
            initView();
        }
    }


    /**
     * 界面赋值
     */
    public void initView() {
        //Z订单状态为4 完成状态  只能看 不能做操作
        if (mTaskinfoBean.getStatus() == 4) {
            etRemark.setEnabled(false);
            etTaobaoNumber.setEnabled(false);
            tv_commit.setVisibility(View.GONE);
        } else {
            etRemark.setEnabled(true);
            etTaobaoNumber.setEnabled(true);
            tv_commit.setVisibility(View.VISIBLE);
        }

        if (!TextUtils.isEmpty(mTaskinfoBean.getBuy())) {
            etTaobaoNumber.setVisibility(View.VISIBLE);
            etTaobaoNumber.setText((mTaskinfoBean.getBuy() + ""));
        }


//        etTaobaoNumber.setOnFocusChangeListener(new View.OnFocusChangeListener() {
//            @Override
//            public void onFocusChange(View v, boolean hasFocus) {
//                Log.d("Debug", "focus 离开了界面");
//                if (etTaobaoNumber != null) {
//                    updateTaskinfo(etTaobaoNumber.getText().toString(), 2, 0);
//                }
//            }
//        });


        etTaobaoNumber.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                if (delayRun != null) {
                    //每次editText有变化的时候，则移除上次发出的延迟线程
                    handler.removeCallbacks(delayRun);
                }
                //延迟800ms，如果不再输入字符，则执行该线程的run方法
                handler.postDelayed(delayRun, 800);

            }
        });


        if (!TextUtils.isEmpty(mTaskinfoBean.getRemark())) {
            etRemark.setVisibility(View.VISIBLE);
            etRemark.setText((mTaskinfoBean.getRemark() + ""));
        }

//        etRemark.setOnFocusChangeListener(new View.OnFocusChangeListener() {
//            @Override
//            public void onFocusChange(View v, boolean hasFocus) {
//                Log.d("Debug", "focus 离开了界面");
//                if (etRemark != null) {
//                    updateTaskinfo(etRemark.getText().toString(), 3, 0);
//                }
//            }
//        });

        etRemark.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                if (delayRun1 != null) {
                    //每次editText有变化的时候，则移除上次发出的延迟线程
                    handler1.removeCallbacks(delayRun1);
                }
                //延迟800ms，如果不再输入字符，则执行该线程的run方法
                handler1.postDelayed(delayRun1, 800);

            }
        });


        if (!TextUtils.isEmpty(mTaskinfoBean.getPhotos())) {
            if (mTaskinfoBean.getPhotos().contains(",")) {
                String[] split = mTaskinfoBean.getPhotos().split(",");
                for (int i = 0; i < split.length; i++) {
                    photoPictureList.add(new ImageBean(split[i], ""));
                }
            } else {
                photoPictureList.add(new ImageBean(mTaskinfoBean.getPhotos(), ""));
            }
            mPictureAdapter.notifyDataSetChanged();
        }


        if (!TextUtils.isEmpty(mTaskinfoBean.getOthers())) {
            if (mTaskinfoBean.getOthers().contains(",")) {
                String[] split = mTaskinfoBean.getOthers().split(",");
                for (int i = 0; i < split.length; i++) {
                    otherPictureList.add(new ImageBean(split[i], ""));
                }
            } else {
                otherPictureList.add(new ImageBean(mTaskinfoBean.getOthers(), ""));
            }
            mOtherAdapter.notifyDataSetChanged();
        }


    }


    private Handler handler = new Handler();
    private Handler handler1 = new Handler();

    /**
     * 延迟线程，看是否还有下一个字符输入
     */
    private Runnable delayRun = new Runnable() {

        @Override
        public void run() {
            if (etTaobaoNumber != null) {
                //在这里调用服务器的接口，获取数据
                updateTaskinfo(etTaobaoNumber.getText().toString(), 2, 0);
            }
        }
    };
    /**
     * 延迟线程，看是否还有下一个字符输入
     */
    private Runnable delayRun1 = new Runnable() {

        @Override
        public void run() {
            if (etRemark != null) {
                //在这里调用服务器的接口，获取数据
                updateTaskinfo(etRemark.getText().toString(), 3, 0);
            }
        }
    };


    /**
     * @param type 0是添加图片 1 删除图片 2卖家淘宝账号 3.修改备注
     */
    private void updateTaskinfo(String message, int type, int position) {
        String token = PrefShare.getInstance(getActivity()).getString("token");
        String userId = PrefShare.getInstance(getActivity()).getString("userId");
//        DialogHelper
        Map<String, String> params = new HashMap<>();
        params.put("token", token);
        params.put("userid", userId);
        params.put("taskid", taskId + "");
        switch (type) {
            case 0:
            case 1:
                if (IsGridPhoto) {
                    params.put("photos", message);
                } else {
                    params.put("others", message);
                }
                break;
            case 2:
                params.put("buy", message);
                break;
            case 3:
                params.put("remark", message);
                break;
        }
        HttpUtils.post().url(AppConfig.ORDER_UPDATETASKINFO)
                .params(params)
                .build()
                .execute(new BaseCallback<TaskInfoBean>(TaskInfoBean.class) {
                    @Override
                    public void onResponse(ObjectResult<TaskInfoBean> result) {
//                        DialogHelper.dismissProgressDialog();
                        Log.d("Debug", "到达请求这里---");
                        if (Result.checkSuccess(getActivity(), result)) {
                            try {
                                switch (type) {
                                    case 0:
                                        if (IsGridPhoto) {
                                            mTaskinfoBean.setPhotos(message);
                                        } else {
                                            mTaskinfoBean.setOthers(message);
                                        }
                                        break;
                                    case 1:
                                        if (IsGridPhoto) {
                                            photoPictureList.remove(position);
                                            mPictureAdapter.notifyDataSetChanged();
                                            mTaskinfoBean.setPhotos(message);
                                        } else {
                                            otherPictureList.remove(position);
                                            mOtherAdapter.notifyDataSetChanged();
                                            mTaskinfoBean.setOthers(message);
                                        }
                                        ToastUtil.showShort("删除成功");
                                        break;
                                    case 2:
                                        mTaskinfoBean.setBuy(message);
                                        break;
                                    case 3:
                                        mTaskinfoBean.setRemark(message);
                                        break;
                                }
                                StyledDialog.dismiss(gloablDialog);
                            } catch (Exception E) {

                            }
                        }

                    }

                    @Override
                    public void onError(Call call, Exception e) {
                        StyledDialog.dismiss(gloablDialog);
//                        DialogHelper.dismissProgressDialog();
//                        ToastUtil.showErrorNet(LoginActivity.this);
                    }
                });
    }


    /**
     * 获取订单最新消息
     */
    private void getTaskinfo() {
        Map<String, String> params = new HashMap<>();
        params.put("taskid", taskId);
        HttpUtils.post().url(AppConfig.ORDER_TASKINFO)
                .params(params)
                .addSecret()
                .build()
                .execute(new BaseCallback<TaskInfoBean>(TaskInfoBean.class) {
                    @Override
                    public void onResponse(ObjectResult<TaskInfoBean> result) {
//                        DialogHelper.dismissProgressDialog();
                        Log.d("Debug", "到达请求这里---");
                        if (Result.checkSuccess(getActivity(), result)) {
                            submitTask(result.getData());
                        }
                    }

                    @Override
                    public void onError(Call call, Exception e) {
//                        DialogHelper.dismissProgressDialog();
//                        ToastUtil.showErrorNet(LoginActivity.this);
                    }
                });
    }


    /**
     * 提交任务
     */
    private void submitTask(TaskInfoBean bean) {
        Map<String, String> params = new HashMap<>();

        SumitTaskJson sumitTaskJson = new SumitTaskJson();
        sumitTaskJson.setTaskid(taskId);
        sumitTaskJson.setBuy(etTaobaoNumber.getText().toString());
        sumitTaskJson.setPhotos(bean.getTaskinfo().getPhotos());
        sumitTaskJson.setOthers(bean.getTaskinfo().getOthers());
        sumitTaskJson.setLat(latitude + "");
        sumitTaskJson.setLng(longitude + "");
        sumitTaskJson.setRemark(etRemark.getText().toString());
        List<TaskInfoBean.OrderinfoBean> orderinfo = bean.getOrderinfo();
        List<TaskInfoBean.OrderinfoBean> objects = new ArrayList<>();
        for (int i = 0; i < orderinfo.size(); i++) {
            objects.add(orderinfo.get(i));
        }
        sumitTaskJson.setOrderinfo(objects);
        String json = JsonUitl.objectToString(sumitTaskJson);

        params.put("json", json);
        HttpUtils.post().url(AppConfig.ORDER_SUBMITTASK)
                .params(params)
                .addSecret()
                .build()
                .execute(new BaseCallback<TaskInfoBean>(TaskInfoBean.class) {
                    @Override
                    public void onResponse(ObjectResult<TaskInfoBean> result) {
//                        DialogHelper.dismissProgressDialog();
                        Log.d("Debug", "到达请求这里---");
                        if (Result.checkSuccess(getActivity(), result)) {
                            ToastUtil.showShort("提交成功");
                            EventBus.getDefault().post(new refushBean());
                            getActivity().finish();
                        }
                    }

                    @Override
                    public void onError(Call call, Exception e) {
//                        DialogHelper.dismissProgressDialog();
//                        ToastUtil.showErrorNet(LoginActivity.this);
                    }
                });
    }

    @Override
    public void onResume() {
        super.onResume();
        bmapView.onResume();
    }

    @Override
    public void onPause() {
        super.onPause();
        //在activity执行onPause时执行mMapView. onPause ()，实现地图生命周期管理
        bmapView.onPause();
    }

    @Override
    protected int getErrorLayoutId() {
        return R.layout.submit_order;
    }

    @Override
    protected int getNormalLayoutId() {
        return R.layout.submit_order;
    }

    @Override
    protected MineFragmentPresenter createPresenter() {
        return new MineFragmentPresenter(getContext(), this);
    }


    @Override
    public void requestFailed(String message) {
        if (mProgressDialog != null) {
            mProgressDialog.dismiss();
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // TODO: inflate a fragment view
        View rootView = super.onCreateView(inflater, container, savedInstanceState);
        EventBus.getDefault().register(this);
        unbinder = ButterKnife.bind(this, rootView);
        return rootView;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        EventBus.getDefault().unregister(this);
        //在activity执行onDestroy时执行mMapView.onDestroy()，实现地图生命周期管理
        unbinder.unbind();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (bmapView != null) {
            bmapView.onDestroy();
        }
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);

    }


    //上传的进度回调
    String accessKeyId = "LTAI4FpBbo7yfZx1waLnveHQ";
    String accessKeySecret = "aymEw4VmeHKuFtnyYVoyDIziQrCLff";
    String endpoint = "http://cdnzkds.zyfjsm.com";
    String bucketName = "gpos-zkds";
    OssService ossService;
    Dialog gloablDialog;


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void XXX(sendImageBean messageEvent) {

        if (taskId == messageEvent.getOrderId()) {
            getActivity().runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    ArrayList<String> photoLocalList = new ArrayList<>();
                    ArrayList<String> otherLocalList = new ArrayList<>();
                    for (int i = 0; i < messageEvent.getImages().size(); i++) {
                        if (IsGridPhoto) {
                            photoPictureList.add(new ImageBean(messageEvent.getImages().get(i)));
                            mPictureAdapter.notifyDataSetChanged();
                            photoLocalList.add(messageEvent.getImages().get(i));
                        } else {
                            otherPictureList.add(new ImageBean(messageEvent.getImages().get(i)));
                            mOtherAdapter.notifyDataSetChanged();
                            otherLocalList.add(messageEvent.getImages().get(i));
                        }
                    }

                    gloablDialog = StyledDialog.buildLoading(getActivity(), "上传中...").show();
                    if (IsGridPhoto) {
                        ossService.ossUploadBefore(getActivity(), taskId + "", photoLocalList, new ArrayList<>(), new OssService.SomeOnUploadListener() {
                            @Override
                            public void onSuccess(List<ImageBean> ossUrls) {
                                //根据本地地址   赋值oss地址
                                for (int i = 0; i < photoPictureList.size(); i++) {
                                    for (int j = 0; j < ossUrls.size(); j++) {
                                        if (photoPictureList.get(i).getLocalUrl().equals(ossUrls.get(j).getLocalUrl())) {
                                            photoPictureList.get(i).setOssUrl(ossUrls.get(j).getOssUrl());
                                        }
                                    }
                                }
                                //这里拼接上传地址
                                StringBuilder sb = new StringBuilder();
                                for (int i = 0; i < photoPictureList.size(); i++) {
                                    String ossUrl = photoPictureList.get(i).getOssUrl();
                                    if (i == photoPictureList.size() - 1) {
                                        sb.append(ossUrl);
                                    } else {
                                        sb.append(ossUrl).append(",");
                                    }
                                }
                                updateTaskinfo(sb.toString(), 0, 0);
                                Log.d("ossUploadBefore", "要上传的oss地址" + sb.toString());
                            }
                        });
                    } else {
                        ossService.ossUploadBefore(getActivity(), taskId + "", otherLocalList, new ArrayList<>(), new OssService.SomeOnUploadListener() {
                            @Override
                            public void onSuccess(List<ImageBean> ossUrls) {
                                //根据本地地址   赋值oss地址
                                for (int i = 0; i < otherPictureList.size(); i++) {
                                    for (int j = 0; j < ossUrls.size(); j++) {
                                        if (otherPictureList.get(i).getLocalUrl().equals(ossUrls.get(j).getLocalUrl())) {
                                            otherPictureList.get(i).setOssUrl(ossUrls.get(j).getOssUrl());
                                        }
                                    }
                                }
                                //这里拼接上传地址
                                StringBuilder sb = new StringBuilder();
                                for (int i = 0; i < otherPictureList.size(); i++) {
                                    String ossUrl = otherPictureList.get(i).getOssUrl();
                                    if (i == otherPictureList.size() - 1) {
                                        sb.append(ossUrl);
                                    } else {
                                        sb.append(ossUrl).append(",");
                                    }
                                }
                                updateTaskinfo(sb.toString(), 0, 0);
                                Log.d("ossUploadBefore", "要上传的oss地址" + sb.toString());
                            }
                        });
                    }
                }
            });

        }


    }

//    String photoPictureoss = "";
//    String otherPictureoss = "";
//
//    public void uploadOssImage(OssService ossService, int position, int sumNumber, String loacalImageurl) {
////开始上传，参数分别为content，上传的文件名filename，上传的文件路径filePath
//        ossService.beginupload(getActivity(), position, sumNumber, createOssurl(), loacalImageurl, new OssService.OnUploadListener() {
//            @Override
//            public void onProgress(double progress) {
//
//            }
//
//            @Override
//            public void onSuccess(int position, int sumNumber, String uploadPath, String imageUrl) {
//                Log.d("Debug", "图片上传成功回调" + "上传地址" + uploadPath);
//                Log.d("Debug", "图片上传成功回调" + "阿里云地址" + imageUrl);
//                Log.d("Debug", "返回的position" + position + "总数量为" + sumNumber);
//                if (IsGridPhoto) {
//                    //照相拍照
//                    for (int i = 0; i < photoPictureList.size(); i++) {
//                        if (photoPictureList.get(i).getLocalUrl().equals(uploadPath)) {
//                            photoPictureList.get(i).setOssUrl(imageUrl);
//                            break;
//                        }
//                    }
//                    photoPictureoss = photoPictureoss + imageUrl + ",";
//                    Log.d("Debug", "0ss地址" + photoPictureoss);
//                    String sendurl = "";
//                    if (!TextUtils.isEmpty(mTaskinfoBean.getPhotos())) {
//                        sendurl = mTaskinfoBean.getPhotos() + "," + photoPictureoss.substring(0, photoPictureoss.length() - 1);
//                    } else {
//                        sendurl = photoPictureoss.substring(0, photoPictureoss.length() - 1);
//                    }
//                    Log.d("Debug", "返回的图片地址是" + sendurl);
//                    updateTaskinfo(sendurl, 0, 0);
//                } else {
//                    //其他图片
//                    for (int i = 0; i < otherPictureList.size(); i++) {
//                        if (otherPictureList.get(i).getLocalUrl().equals(uploadPath)) {
//                            otherPictureList.get(i).setOssUrl(imageUrl);
//                            break;
//                        }
//                    }
//                    otherPictureoss = otherPictureoss + imageUrl + ",";
//                    Log.d("Debug", "0ss地址" + photoPictureoss);
//                    String sendurl = "";
//                    if (!TextUtils.isEmpty(mTaskinfoBean.getOthers())) {
//                        sendurl = mTaskinfoBean.getOthers() + "," + otherPictureoss.substring(0, otherPictureoss.length() - 1);
//                    } else {
//                        sendurl = otherPictureoss.substring(0, otherPictureoss.length() - 1);
//                    }
//                    Log.d("Debug", "返回的图片地址是" + sendurl);
//                    updateTaskinfo(sendurl, 0, 0);
//
//                }
//
//
//            }
//
//            @Override
//            public void onFailure(int position) {
//
//            }
//        });
//    }
//
//    /**
//     * 创建oss上传地址
//     *
//     * @return
//     */
//    public String createOssurl() {
//        String userid = PrefShare.getInstance(getActivity()).getString("userId");
//        String orderId = mTaskinfoBean.getId() + "";
//        String random = (int) ((Math.random() * 9 + 1) * 1000) + "";
//        String url = "order/" + getTime() + "/" + userid + orderId + System.currentTimeMillis() + random;
//        return url;
//    }
//
//    public String getTime() {
//        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
//        Date date = new Date(System.currentTimeMillis());
//        String time = sdf.format(date);
//        return time;
//    }


    @OnClick({R.id.tv_commit})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_commit:
                getTaskinfo();
                break;
        }
    }
}